<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */

namespace MoChat\App\WorkContact\Logic;

use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Utils\Arr;
use Hyperf\Utils\Codec\Json;
use MoChat\App\Corp\Constants\WorkUpdateTime\Type;
use MoChat\App\Corp\Contract\CorpContract;
use MoChat\App\Corp\Contract\WorkUpdateTimeContract;
use MoChat\App\WorkContact\Constants\AddWay;
use MoChat\App\WorkContact\Constants\Employee\Status;
use MoChat\App\WorkContact\Constants\Gender;
use MoChat\App\WorkContact\Constants\Room\Type as ContactType;
use MoChat\App\WorkContact\Contract\ContactFieldPivotContract;
use MoChat\App\WorkContact\Contract\WorkContactContract;
use MoChat\App\WorkContact\Contract\WorkContactEmployeeContract;
use MoChat\App\WorkContact\Contract\WorkContactRoomContract;
use MoChat\App\WorkContact\Contract\WorkContactTagContract;
use MoChat\App\WorkContact\Contract\WorkContactTagPivotContract;
use MoChat\App\WorkDepartment\Contract\WorkDepartmentContract;
use MoChat\App\WorkEmployee\Contract\WorkEmployeeContract;
use MoChat\App\WorkEmployee\Contract\WorkEmployeeDepartmentContract;
use MoChat\App\WorkRoom\Contract\WorkRoomContract;
use MoChat\Plugin\ContactStage\Contract\ContactStageContract;

/**
 * 客户列表.
 *
 * Class IndexLogic
 */
class IndexLogic
{
    /**
     * @Inject
     * @var WorkEmployeeDepartmentContract
     */
    protected $workEmployeeDepartmentService;

    /**
     * @Inject
     * @var WorkDepartmentContract
     */
    protected $workDepartmentService;

    /**
     * @Inject
     * @var ContactStageContract
     */
    protected $contactStageService;

    /**
     * @Inject
     * @var WorkContactContract
     */
    protected $workContactService;

    /**
     * 客户表.
     * @Inject
     * @var WorkContactContract
     */
    private $contact;

    /**
     * 员工 - 客户关联.
     * @Inject
     * @var WorkContactEmployeeContract
     */
    private $contactEmployee;

    /**
     * 标签.
     * @Inject
     * @var WorkContactTagContract
     */
    private $contactTag;

    /**
     * 客户 - 标签关联.
     * @Inject
     * @var WorkContactTagPivotContract
     */
    private $workContactTagPivotService;

    /**
     * 用户画像.
     * @Inject
     * @var ContactFieldPivotContract
     */
    private $contactFieldPivot;

    /**
     * 客户群.
     * @Inject
     * @var WorkRoomContract
     */
    private $room;

    /**
     * 客户 - 群关联.
     * @Inject
     * @var WorkContactRoomContract
     */
    private $contactRoom;

    /**
     * 同步时间.
     * @Inject
     * @var WorkUpdateTimeContract
     */
    private $workUpdateTime;

    /**
     * 员工.
     * @Inject
     * @var WorkEmployeeContract
     */
    private $employee;

    /**
     * 企业表.
     * @Inject
     * @var CorpContract
     */
    private $corp;

    /**
     * 参数.
     * @var array
     */
    private $params;

    /**
     * 参数.
     * @var array
     */
    private $result;

    /**
     * @return array
     */
    public function handle(array $params)
    {
        $this->params = $params;
        $this->result = [
            'page' => [
                'perPage' => 20,
                'total' => 0,
                'totalPage' => 0,
            ],
            'list' => [],
            'syncContactTime' => '',
        ];

        // 处理查询条件
        $where = $this->handleWhere($this->params);

        // 标明没有数据
        if (isset($where['flag'])) {
            return $this->result;
        }
        unset($where['flag']);

        // 获取客户列表
        return $this->getContactEmployeeInfo($where);
    }

    public function getFollowUpStatus($followUpStatus): string
    {
        $followStage = $this->contactStageService->getContactStagesByCorpId(user('corpIds')[0], ['id', 'name']);
        if (empty($followStage)) {
            return '';
        }
        $state = [];
        foreach ($followStage as $v) {
            $state[$v['id']] = $v['name'];
        }
        return $state[$followUpStatus] ?? '';
    }

    /**
     * 处理客户列表查询条件.
     * @param $params
     */
    protected function handleWhere($params): array
    {
        $where = [];
        // 企业id
        $where['corpId'] = user()['corpIds'][0];
        // 数据权限 0-全企业，1-本部门数据，2-当前登录人
        if (isset(user()['dataPermission']) && user()['dataPermission'] != 0) {
            // 员工id
            $where['employeeId'] = array_unique(user()['deptEmployeeIds']);
        }

        // 状态为正常
        $where['status'] = Status::NORMAL;

        // 备注搜索
        if (!empty($params['remark'])) {
            $where['remark'] = $params['remark'];
        }
        // 客户来源搜索
        if (is_numeric($params['addWay'])) {
            $where['addWay'] = $params['addWay'];
        }
        // 添加时间搜索
        if (!empty($params['startTime'])) {
            $where['startTime'] = $params['startTime'];
        }
        if (!empty($params['endTime'])) {
            $where['endTime'] = $params['endTime'];
        }

        // 部门成员搜索
        if (!empty($params['employeeId'])) {
            if ($params['employeeId'] == '空') {
                // 查询不出数据 的标识
                $where['flag'] = 1;
            }
            $employeeIds = explode(',', $params['employeeId']);

            if (isset($where['employeeId'])) {
                $where['employeeId'] = array_intersect($where['employeeId'], $employeeIds);
            } else {
                $where['employeeId'] = $employeeIds;
            }
        }

        // 关键词搜索
        if (!empty($params['keyWords'])) {
            $name = $params['keyWords'];
            $contact = $this->contact->getWorkContactsByCorpIdName(user()['corpIds'][0], $name, ['id']);
            if (!empty($contact)) {
                $contactIds = array_column($contact, 'id');
                if (isset($where['contactId'])) {
                    // 取交集
                    $where['contactId'] = array_intersect($where['contactId'], $contactIds);
                } else {
                    $where['contactId'] = $contactIds;
                }
            } else {
                // 查询不出数据 的标识
                $where['flag'] = 1;
            }
        }
        if (!empty($params['contact_id'])){
            $where['contactId'] = $params['contact_id'];
        }
        // 客户编号搜索
        if (!empty($params['businessNo'])) {
            $contact = $this->contact->getWorkContactsByCorpIdBusinessNo(user()['corpIds'][0], $params['businessNo'], ['id']);
            if (!empty($contact)) {
                $contactIds = array_column($contact, 'id');
                if (isset($where['contactId'])) {
                    // 取交集
                    $where['contactId'] = array_intersect($where['contactId'], $contactIds);
                } else {
                    $where['contactId'] = $contactIds;
                }
            } else {
                // 查询不出数据的标识
                $where['flag'] = 1;
            }
        }
        // 客户性别搜索
        if (!empty($this->params['gender']) && $params['gender'] != 3) {
            $contact = $this->contact->getWorkContactsByCorpIdGender(user()['corpIds'][0], $params['gender'], ['id']);
            if (!empty($contact)) {
                $contactIds = array_column($contact, 'id');
                if (isset($where['contactId'])) {
                    // 取交集
                    $where['contactId'] = array_intersect($where['contactId'], $contactIds);
                } else {
                    $where['contactId'] = $contactIds;
                }
            } else {
                // 查询不出数据的标识
                $where['flag'] = 1;
            }
        }
        // 用户画像搜索
        if (is_numeric($params['fieldId']) && $params['fieldId'] != 0) {
            // 查询满足用户画像值的用户id
            $pivot = $this->contactFieldPivot
                ->getContactFieldPivotsByFieldIdValue($params['fieldId'], $params['fieldValue'], ['contact_id']);
            if (!empty($pivot)) {
                $contactIds = array_column($pivot, 'contactId');

                if (isset($where['contactId'])) {
                    // 取交集
                    $where['contactId'] = array_intersect($where['contactId'], $contactIds);
                } else {
                    $where['contactId'] = $contactIds;
                }
            } else {
                // 查询不出数据的标识
                $where['flag'] = 1;
            }
        }

        // 新版-自定义信息筛选-用户画像搜索
        if (!empty($params['fieldList']) && $params['fieldList'] !== '{}') {
            // 查询满足用户画像值的用户id
            $fieldWhere = $this->getFieldWhere(Json::decode($params['fieldList']));
            if (!empty($fieldWhere)) {
                $pivot = $this->contactFieldPivot
                    ->getContactFieldPivotByFieldIdList($fieldWhere, ['contact_id']);
                if (!empty($pivot)) {
                    $contactIds = array_column($pivot, 'contactId');

                    if (isset($where['contactId'])) {
                        // 取交集
                        $where['contactId'] = array_intersect($where['contactId'], $contactIds);
                    } else {
                        $where['contactId'] = $contactIds;
                    }
                } else {
                    // 查询不出数据的标识
                    $where['flag'] = 1;
                }
            }
        }
        // 企业标签搜索
        if (!empty($params['tags']) && $params['tags'] !== '{}') {
            $params['tags'] = Json::decode($params['tags']);
            // 查询在标签里的客户id（1：以下标签满足其中之一，2：以下标签同时满足，3无任何标签）
            if (in_array((int)$params['tags']['type'], [1, 2])) {
                $tagPivot = $this->workContactTagPivotService->getWorkContactTagPivotsByContactTagIdsType($params['tags']['tagIds'], (int)$params['tags']['type'], [], ['contact_id']);
                if (!empty($tagPivot)) {
                    $contactIds = array_unique(array_column($tagPivot, 'contactId'));
                    if (isset($where['contactId'])) {
                        // 取交集
                        $where['contactId'] = array_intersect($where['contactId'], $contactIds);
                    } else {
                        $where['contactId'] = array_merge($contactIds);
                    }
                    $ids = $this->getContactEmployeeIds($contactIds, $params['tags']['tagIds']);
                    empty($ids) || $where['id'] = $ids;
                } else {
                    // 查询不出数据的标识
                    $where['flag'] = 1;
                }
            }
            if ((int)$params['tags']['type'] === 3) {
                $contacts = $this->workContactService->getWorkContactsByCorpId(user()['corpIds'][0], ['id']);
                $tagPivot = $this->workContactTagPivotService->getWorkContactTagPivotsByContactTagIdsType($params['tags']['tagIds'], 3, array_column($contacts, 'id'), ['contact_id']);
                if (!empty($tagPivot)) {
                    $contactIds = array_unique(array_column($tagPivot, 'contactId'));
                    if (isset($where['contactId'])) {
                        // 取差集
                        $where['contactId'] = array_diff($where['contactId'], $contactIds);
                    } else {
                        $where['contactId'] = array_column($contacts, 'id');
                        // 取差集
                        $where['contactId'] = array_diff($where['contactId'], $contactIds);
                    }
                } else {
                    // 查询不出数据的标识
                    $where['flag'] = 1;
                }
            }
        }
        // 流失状态搜索
        if (!empty($params['lossStatus'])) {
            $where['status'] = (int)$params['lossStatus'] === 1 ? 1 : [2, 3];
        }
        // 群聊搜索
        if (!empty($params['roomId'])) {
            $roomIds = explode(',', $params['roomId']);
            // 查询在群聊里的客户id
            $roomInfo = $this->contactRoom->getWorkContactRoomsByRoomIds($roomIds, ['contact_id']);
            if (!empty($roomInfo)) {
                $contactIds = array_unique(array_column($roomInfo, 'contactId'));
                if (isset($where['contactId'])) {
                    // 取交集
                    $where['contactId'] = array_intersect($where['contactId'], $contactIds);
                } else {
                    $where['contactId'] = $contactIds;
                }
            } else {
                // 查询不出数据的标识
                $where['flag'] = 1;
            }
        }
        // 客户持群数搜索
        if (is_numeric($params['groupNum']) && $params['groupNum'] != 3) {
            $roomInfo = $this->contactRoom->getWorkContactRoomNum();
            if (!empty($roomInfo)) {
                // 查出来有群的客户id
                $noContactIds = array_column($roomInfo, 'contactId');
                // 搜索条件为无群
                if ($params['groupNum'] == 0) {
                    $where['noContactId'] = $noContactIds;
                } else {
                    $contactIds = [];
                    foreach ($roomInfo as &$raw) {
                        // 搜索条件为一个群
                        if ($params['groupNum'] == 1 && $raw['roomTotal'] == $params['groupNum']) {
                            $contactIds[] = $raw['contactId'];
                        }
                        // 搜索条件为多群
                        if ($params['groupNum'] == 2 && $raw['roomTotal'] >= 2) {
                            $contactIds[] = $raw['contactId'];
                        }
                    }
                    unset($raw);

                    if (isset($where['contactId'])) {
                        $where['contactId'] = array_intersect($where['contactId'], $contactIds);
                    } else {
                        $where['contactId'] = $contactIds;
                    }
                }
            } else {
                // 客户均没有群但是搜索条件不是无群时 查不出来数据
                if ($params['groupNum'] != 0) {
                    // 查询不出数据的标识
                    $where['flag'] = 1;
                }
            }
        }

        // 交集为空时 即查不出来数据
        if (isset($where['contactId']) && empty($where['contactId'])) {
            $where['flag'] = 1;
        }
        //绑定类型:1已绑定客户的联系人;2未绑定客户的联系人;3绑定多客户的联系人;4添加多名员工的联系人
        if ($params['bindingType'] == 1) {
            $contactIds = Db::table('client_contact_pivot')->pluck('contact_id');
            $contactIds || $contactIds = collect([]);
            $contactIds = $contactIds->toArray();
            $where['bindingTypeIds'] = $contactIds;
        }
        if ($params['bindingType'] == 2) {
            $contactIds = Db::table('client_contact_pivot')->pluck('contact_id');
            $contactIds || $contactIds = collect([]);
            $contactIds = $contactIds->toArray();
            $where['bindingTypeNotIds'] = $contactIds;
        }
        if ($params['bindingType'] == 3) {
            $contactIds = Db::table('client_contact_pivot')
                ->havingRaw("count>1")
                ->groupBy(['contact_id'])
                ->select([
                    'contact_id',
                    Db::raw('COUNT(*) as count')
                ])->get();
            $contactIds || $contactIds = collect([]);
            $contactIds = $contactIds->toArray();
            $where['bindingTypeMoreIds'] = array_column($contactIds, 'contact_id');
        }
        if ($params['bindingType'] == 4) {
            $contactIds = Db::table('work_contact_employee')
                ->havingRaw("count>1")
                ->groupBy(['contact_id'])
                ->select([
                    'contact_id',
                    Db::raw('COUNT(*) as count')
                ])->get();
            $contactIds || $contactIds = collect([]);
            $contactIds = $contactIds->toArray();
            $where['bindingTypeMoreEmployeeIds'] = array_column($contactIds, 'contact_id');;
        }
        return $where;
    }

    private function getFieldWhere(array $fieldWhere): string
    {
        $raw = '';
        foreach ($fieldWhere['rules'] as $item) {
            if ((int)$item['fieldId'] > 0) {
                $queryType = $this->getQueryType($item['queryType']);
                $query = "(`contact_field_id` ={$item['fieldId']} AND `value` {$queryType} '{$item['fieldValue']}')";
                if ($queryType === 'like' || $queryType === 'not like') {
                    $query = "(`contact_field_id` ={$item['fieldId']} AND `value` {$queryType} '%{$item['fieldValue']}%')";
                }
                empty($raw) && $raw = $query;
                !empty($raw) && $raw .= ' ' . $fieldWhere['condition'] . ' ' . $query;
            }
        }

        return $raw;
    }

    private function getQueryType($queryType)
    {
        $list = ['equal' => '=', 'notEqual' => '<>', 'notNull' => '<>', 'null' => '=', 'like' => 'like', 'notLike' => 'not like'];
        return $list[$queryType];
    }

    private function getContactEmployeeIds(array $contactIds, array $tagIds): array
    {
        $contactEmployees = $this->contactEmployee->getWorkContactEmployeesByContactIds($contactIds, ['id', 'employee_id', 'contact_id']);
        foreach ($contactEmployees as $key => $val) {
            $contactTags = $this->workContactTagPivotService->getWorkContactTagPivotsByContactIdsEmployeeIdsTagIds([$val['contactId']], [$val['employeeId']], $tagIds, 1);
            if (empty($contactTags)) {
                unset($contactEmployees[$key]);
            }
        }
        if (empty($contactEmployees)) {
            return [];
        }
        return array_column($contactEmployees, 'id');
    }

    /**
     * 获取客户列表.
     * @param $where
     * @return array
     */
    private function getContactEmployeeInfo($where)
    {
        $columns = [
            'id',
            'employee_id',
            'contact_id',
            'remark',
            'create_time',
            'add_way',
            'last_message_time',
            'status',
        ];

        // 查询数据
        $info = $this->contactEmployee->getWorkContactEmployeeIndex(
            $where,
            $columns,
            (int)$this->params['perPage'],
            (int)$this->params['page']
        );

        if (empty($info['data'])) {
            return $this->result;
        }

        // 客户id
        $contactIds = array_unique(array_column($info['data'], 'contactId'));
        // 员工id
        $employeeIds = array_unique(array_column($info['data'], 'employeeId'));
        // 查询客户基础信息
        $contact = $this->getContactInfo($contactIds);
        // 查询客户所在群
        $roomName = $this->getContactRoom($contactIds);
        // 查询客户归属成员信息
        $employee = $this->getEmployee($employeeIds);
        // 查询客服所属部门
        $department = $this->getEmployeeDepartment($employeeIds);
        // 客户关联信息
        $clientContacts = Db::table('client_contact_pivot as pivot')
            ->join('client as client','client.id','=','pivot.client_id')
            ->whereIn('pivot.contact_id',$contactIds)->select([
                'contact_id','client_id',
                'client.enterprise_name as b2b_client_name'
            ])->get();
        $clientContacts||$clientContacts=collect([]);
        $clientContacts=$clientContacts->toArray();
        foreach ($info['data'] as &$raw) {
            $raw['clientNames']='';
            foreach ($clientContacts as $cont){
                if ($cont->contact_id==$raw['contactId']){
                    $raw['clientNames'].=$cont->b2b_client_name.',';
                }
            }
            $raw['clientNames']=!empty($raw['clientNames'])?substr($raw['clientNames'],0,strlen($raw['clientNames'])-1):'';
            if (empty($contact[$raw['contactId']])) {
                $followUpStatus = '新客户';
            } else {
                $followUpStatus = $this->getFollowUpStatus($contact[$raw['contactId']]['followUpStatus']);
                if (empty($followUpStatus)) {
                    $followUpStatus = '新客户';
                }
            }
            $raw['followUpStatus'] = $followUpStatus;
            $raw['addWayText'] = AddWay::$Enum[$raw['addWay']] ?? '';
            $raw['genderText'] = '';
            $raw['businessNo'] = '';
            $raw['name'] = '';
            $raw['avatar'] = '';
            if (isset($contact[$raw['contactId']])) {
                $raw['businessNo'] = $contact[$raw['contactId']]['businessNo'];
                $raw['name'] = $contact[$raw['contactId']]['name'];
                $raw['avatar'] = $contact[$raw['contactId']]['avatar'] ? file_full_url($contact[$raw['contactId']]['avatar']) : $contact[$raw['contactId']]['avatar'];
                $raw['gender'] = $contact[$raw['contactId']]['gender'];
                $raw['genderText'] = Gender::getMessage($contact[$raw['contactId']]['gender']);
            }

            $raw['roomName'] = [];
            if (isset($roomName[$raw['contactId']])) {
                $raw['roomName'] = $roomName[$raw['contactId']]['roomName'];
            }

            $raw['employeeName'] = [];
            if (isset($employee[$raw['employeeId']])) {
//                $raw['employeeName'] = $employee[$raw['employeeId']]['corpName'] . ' ' . $employee[$raw['employeeId']]['name'];
                $raw['employeeName'] = $employee[$raw['employeeId']]['name'];
            }
            // 客服部门
            $raw['departmentName'] = empty($department[$raw['employeeId']]) ? [] : array_unique($department[$raw['employeeId']]);

            // 查询客户标签
            $raw['tag'] = $this->getContactTag($raw['contactId'], $raw['employeeId']);
            // 判断该客户是否是当前登录人的客户
            $raw['isContact'] = 1; // 是
            if (user()['workEmployeeId'] != $raw['employeeId']) {
                $raw['isContact'] = 2;
            }

            $raw['user'] = user();
        }
        unset($raw);

        // 返回数据
        $data = [
            'page' => [
                'perPage' => isset($info['per_page']) ? $info['per_page'] : 20,
                'total' => isset($info['total']) ? $info['total'] : 0,
                'totalPage' => isset($info['last_page']) ? $info['last_page'] : 0,
            ],
            'list' => empty($info['data']) ? [] : $info['data'],
            'syncContactTime' => $this->getTime(),
        ];

        return $data;
    }

    private function getEmployeeDepartment($employeeIds): array
    {
        // 客服部门
        $department = $this->workEmployeeDepartmentService->getWorkEmployeeDepartmentsByEmployeeIds($employeeIds, ['employee_id', 'department_id']);
        if (empty($department)) {
            return [];
        }
        $departmentIds = array_column($department, 'departmentId');
        // 部门信息
        $departmentNames = $this->workDepartmentService->getWorkDepartmentsById($departmentIds, ['id', 'name']);
        if (empty($departmentNames)) {
            return [];
        }
        $departmentName = [];
        foreach ($departmentNames as $name) {
            $departmentName[$name['id']] = $name['name'];
        }
        // 客服部门名称
        $employeeDepartment = [];
        foreach ($department as $item) {
            $employeeDepartment[$item['employeeId']][] = $departmentName[$item['departmentId']]??"";
        }
        return $employeeDepartment;
    }

    /**
     * 获取客户信息.
     * @param $contactIds
     * @return array
     */
    private function getContactInfo($contactIds)
    {
        $contact = $this->contact->getWorkContactsById($contactIds);
        if (!empty($contact)) {
            $contact = array_column($contact, null, 'id');
        }

        return $contact;
    }

    /**
     * 查询员工信息.
     * @param $employeeIds
     * @return array
     */
    private function getEmployee($employeeIds)
    {
        // 根据员工id查询员工信息、企业id
        $employeeInfo = $this->employee->getWorkEmployeesById($employeeIds, ['id', 'name', 'corp_id']);

        if (empty($employeeInfo)) {
            return [];
        }

        $corpIds = array_unique(array_column($employeeInfo, 'corpId'));

        // 查询企业名称
        $corpInfo = $this->corp->getCorpsById($corpIds, ['id', 'name']);
        if (empty($corpInfo)) {
            return [];
        }
        $corpInfo = array_column($corpInfo, null, 'id');

        foreach ($employeeInfo as &$raw) {
            $raw['corpName'] = '';

            if (isset($corpInfo[$raw['corpId']])) {
                $raw['corpName'] = $corpInfo[$raw['corpId']]['name'];
            }
        }

        unset($raw);

        $employeeInfo = array_column($employeeInfo, null, 'id');

        return $employeeInfo;
    }

    /**
     * 获取客户标签.
     * @param $contactId
     * @param $employeeId
     * @return array
     */
    private function getContactTag($contactId, $employeeId)
    {
        $contactTag = $this->workContactTagPivotService->getWorkContactTagPivotsByOtherId($contactId, $employeeId);
        if (empty($contactTag)) {
            return [];
        }

        $tagIds = array_unique(array_column($contactTag, 'contactTagId'));
        // 根据标签id查询标签名称
        $tagInfo = $this->contactTag->getWorkContactTagsById($tagIds, ['id', 'name']);

        if (empty($tagInfo)) {
            return [];
        }

        $tagInfo = array_column($tagInfo, null, 'id');

        $tagName = [];
        foreach ($contactTag as &$raw) {
            if (isset($tagInfo[$raw['contactTagId']])) {
                $tagName[] = $tagInfo[$raw['contactTagId']]['name'];
            }
        }
        unset($raw);

        $tagName = array_unique($tagName);

        return $tagName;
    }

    /**
     * 获取客户所在群.
     * @param $contactIds
     * @return array
     */
    private function getContactRoom($contactIds)
    {
        $contactRoom = $this->contactRoom->getWorkContactRoomsByContactIdsType($contactIds, (int)ContactType::CONTACT, ['contact_id', 'room_id']);
        if (empty($contactRoom)) {
            return [];
        }

        $roomIds = array_column($contactRoom, 'roomId');
        // 根据群id查询群名称
        $roomInfo = $this->room->getWorkRoomsById($roomIds, ['id', 'name']);

        if (!empty($roomInfo)) {
            $roomInfo = array_column($roomInfo, null, 'id');
        }

        $contactData = [];
        foreach ($contactRoom as &$raw) {
            $raw['roomName'] = '';
            if (isset($roomInfo[$raw['roomId']])) {
                $raw['roomName'] = $roomInfo[$raw['roomId']]['name'];
            }

            if (isset($contactData[$raw['contactId']])) {
                $contactData[$raw['contactId']]['roomName'][] = $raw['roomName'];
            } else {
                $tmp = [];
                $tmp['roomName'][] = $raw['roomName'];

                $contactData[$raw['contactId']] = $tmp;
            }
        }

        unset($raw);

        return $contactData;
    }

    /**
     * 获取最后一次同步客户的时间.
     * @return mixed
     */
    private function getTime()
    {
        $type = Type::CONTACT;

        $res = $this->workUpdateTime->getWorkUpdateTimeByCorpIdType(user()['corpIds'], (int)$type, ['last_update_time']);

        return empty($res) ? '' : end($res)['lastUpdateTime'];
    }
}
